package controller

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/internal/routers"
	"seawolf-admin-go/internal/service/AdminService"
	"seawolf-admin-go/internal/service/OrgMemberService"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
)

type cOrgMember struct {
	*BaseController
}

func NewOrgMemberController(group *ghttp.RouterGroup, defaultVersion string) {
	// 初始化内部变量
	inputReq := &BaseReq.I{}
	c := &cOrgMember{&BaseController{Req: inputReq}}
	c.New(group, defaultVersion)
}

func (c *cOrgMember) New(group *ghttp.RouterGroup, defaultVersion string) {
	ctx := context.Background()
	var leftJoin []*BaseReq.QueryOpLeftJoin
	dbPrefixTmp, _ := g.Cfg().Get(ctx, "database.prefix", "")
	dbPrefix := dbPrefixTmp.String()
	leftJoin = append(leftJoin, &BaseReq.QueryOpLeftJoin{
		TableInfo: dbPrefix + "sys_department sd",
		Condition: "a.dept_id = sd.id",
	})
	// 配置表名
	c.Req = &BaseReq.I{
		TableName:          "admin",
		InfoIgnoreProperty: "password,password_salt,delete_at",
		SoftDeleteField:    "delete_at",
		PageQueryOp: &BaseReq.QueryOp{
			SelectFields: []string{
				"a.id",
				"a.account",
				"a.dept_id",
				"a.realname",
				"a.nickname",
				"a.avatar",
				"a.phone",
				"a.remark",
				"a.status",
				"a.create_at",
				"sd.name AS departmentName",
			},
			KeyWordLikeFields: []string{
				"a.account",
				"a.realname",
				"a.nickname",
			},
			AsName:   "a",
			LeftJoin: leftJoin,
			OtherWhere: func(r *ghttp.Request) g.Map {
				data := g.Map{
					"a.is_org": 1,
				}
				departmentIds := r.Get("departmentIds")
				if departmentIds != nil {
					data["a.dept_id IN (?)"] = departmentIds.Ints()
				}
				return data
			},
		},
		ListQueryOp: &BaseReq.QueryOp{
			OtherWhere: func(r *ghttp.Request) g.Map {
				return g.Map{
					"is_org": 1,
				}
			},
		},
		InfoQueryOp: &BaseReq.QueryOp{
			OtherWhere: func(r *ghttp.Request) g.Map {
				return g.Map{
					"is_org": 1,
				}
			},
		},
		AddInsertData: func(r *ghttp.Request) g.Map {
			return g.Map{
				"is_org":         1,
				"account_prefix": "om:",
			}
		},
		UpdateInsertData: func(r *ghttp.Request) g.Map {
			return g.Map{
				"is_org":         1,
				"account_prefix": "om:",
			}
		},
		AddBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
			count, err := db.GetUnSafaTable(ctx, "admin").Handler(db.SoftDeleteHandler).Where("account_prefix = ? AND account = ?",
				data["account_prefix"], data["account"]).Fields("id").Count()
			if err != nil {
				return response.FailByRequestMessage(nil, err.Error())
			}
			if count > 0 {
				return response.FailByRequestMessage(nil, "账号已存在")
			}
			return response.SuccessByRequest(r)
		},
		UpdateBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
			count, err := db.GetUnSafaTable(ctx, "admin").Handler(db.SoftDeleteHandler).Where(
				"account_prefix = ? AND account = ? AND id != ?",
				data["account_prefix"], data["account"], r.Get("id")).Fields("id").Count()
			if err != nil {
				return response.FailByRequestMessage(nil, err.Error())
			}
			if count > 0 {
				return response.FailByRequestMessage(nil, "账号已存在")
			}
			return response.SuccessByRequest(r)
		},
		InfoAfterFn: func(r *ghttp.Request, result map[string]interface{}) (map[string]interface{}, error) {
			if result == nil {
				return result, nil
			}
			// 取部门名称
			dName, err := db.GetUnSafaTable(ctx, "sys_department").Where("id", result["dept_id"]).Fields("name").Value()
			if err != nil {
				return nil, err
			}
			result["departmentName"] = dName.String()
			// 取角色
			roleIds, err := db.GetUnSafaTable(ctx, "admin_role a").
				InnerJoin("sys_role r", "r.id=a.role_id").
				Where("r.is_org=1 AND a.admin_id=?", result["id"]).Fields("role_id").Array()
			if err != nil {
				return nil, err
			}
			if roleIds != nil {
				result["roleIdList"] = gconv.SliceInt(roleIds)
			}
			return result, nil
		},
	}
	// 处理初始化方法和结束方法中间件
	group.Middleware(func(r *ghttp.Request) {
		c.Init(r)
		r.Middleware.Next()
		c.Shut(r)
	})
	// 注册基础路由
	RegBase(group, c, nil)

	// 重置密码
	group.POST("/resetPass", func(r *ghttp.Request) {
		routers.MethodCallWithVersionStrategy(r, map[string]interface{}{
			"1.0.0": c.ResetPass,
		}, defaultVersion, routers.DemoteStrategy)
	})
}

func (c *cOrgMember) ResetPass(r *ghttp.Request) *response.JsonResponse {
	if err := c.checkIds(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	c.Req.AdminId = r.GetCtxVar("admin_id", 0).Int()
	return AdminService.ResetPass(r, c.Req)
}
func (c *cOrgMember) Add(r *ghttp.Request) *response.JsonResponse {
	return OrgMemberService.Add(r, c.Req)
}
func (c *cOrgMember) Update(r *ghttp.Request) *response.JsonResponse {
	c.Req.Id = r.Get("id", "").String()
	return OrgMemberService.Update(r, c.Req)
}
